package com.getpebble.android.jskit.webapps;

import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.framework.appmessage.AppMessage;
import com.getpebble.android.framework.appmessage.AppMessage.AppMessageCommand;
import com.getpebble.android.framework.appmessage.BinaryPebbleDictionary;
import com.getpebble.android.framework.appmessage.PebbleDictionary;
import com.getpebble.android.framework.appmessage.PebbleTuple.TupleType;
import com.getpebble.android.framework.notification.gmail.GmailCheckerService;
import com.sun.mail.imap.IMAPStore;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PebbleBabel {
    protected static int GREATEST_HARDCODED_KEY_VALUE = 300;
    public static final UUID NullUuid = new UUID(0, 0);
    private static final String TAG = PebbleBabel.class.getSimpleName();
    protected static String[] sAppInfoFixedKeys = initAppInfoFixedKeys();
    protected static Map<String, Map<String, Integer>> sStringToIntKeyTranslatorForPushMessages = initMappingsForPushMessages();
    public UUID mActiveAppUuid;
    public final UUID mNativeClientAppUuid;
    protected Map<String, Map<String, Integer>> mStringToIntKeyTranslatorForAppSpecificMessages;

    static /* synthetic */ class AnonymousClass1 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$appmessage$PebbleTuple$TupleType = new int[TupleType.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$appmessage$PebbleTuple$TupleType[TupleType.BYTES.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$appmessage$PebbleTuple$TupleType[TupleType.STRING.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$appmessage$PebbleTuple$TupleType[TupleType.UINT.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$appmessage$PebbleTuple$TupleType[TupleType.INT.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    public static class AppInfoBlocks {
        public JSONObject infoBlock = null;
        public JSONObject keysMapBlock = null;
        public long keysUpdateSerial = Long.MIN_VALUE;
    }

    public static abstract class JsonField {
        public final Integer AppMessageIntKey;

        public abstract PebbleDictionary emitAppended(PebbleDictionary pebbleDictionary);

        private JsonField() {
            this.AppMessageIntKey = Integer.valueOf(0);
        }

        protected JsonField(int appMessageKey) {
            this.AppMessageIntKey = Integer.valueOf(appMessageKey);
        }
    }

    public static class JsonFieldByteArray extends JsonField {
        protected byte[] FinalByteValues;
        protected JSONArray RawJsonArray;
        protected String[] UnprocessedValues;

        public JsonFieldByteArray(int appMessageKey, JSONArray value) {
            super(appMessageKey);
            if (value != null) {
                this.RawJsonArray = value;
            } else {
                this.RawJsonArray = new JSONArray();
            }
            this.UnprocessedValues = null;
            this.FinalByteValues = null;
        }

        public PebbleDictionary emit() {
            PebbleDictionary d = new BinaryPebbleDictionary();
            if (this.FinalByteValues == null) {
                if (this.UnprocessedValues != null) {
                    processStringValuesToBytes();
                } else {
                    processJsonArrayToBytes();
                }
            }
            d.addBytesCopy(this.AppMessageIntKey.intValue(), this.FinalByteValues);
            return d;
        }

        public PebbleDictionary emitAppended(PebbleDictionary target) {
            if (target == null) {
                return emit();
            }
            if (this.FinalByteValues == null) {
                if (this.UnprocessedValues != null) {
                    processStringValuesToBytes();
                } else {
                    processJsonArrayToBytes();
                }
            }
            target.addBytesCopy(this.AppMessageIntKey.intValue(), this.FinalByteValues);
            return target;
        }

        protected void processJsonArrayToBytes() {
            if (this.RawJsonArray == null) {
                this.FinalByteValues = new byte[0];
                return;
            }
            int nElements = this.RawJsonArray.length();
            if (nElements < 1) {
                this.FinalByteValues = new byte[0];
                return;
            }
            int i;
            ArrayList<Byte> results = new ArrayList();
            for (i = 0; i < nElements; i++) {
                try {
                    Object elementObject = this.RawJsonArray.get(i);
                    if (elementObject instanceof Double) {
                        results.add(Byte.valueOf(((Double) elementObject).byteValue()));
                    } else if (elementObject instanceof Integer) {
                        results.add(Byte.valueOf((byte) (((Integer) elementObject).intValue() % 256)));
                    } else if (elementObject instanceof String) {
                        Byte[] bytes = processSingleStringValue((String) elementObject);
                        if (bytes != null && bytes.length > 0) {
                            results.addAll(Arrays.asList(bytes));
                        }
                    } else if (elementObject instanceof Boolean) {
                        results.add(Byte.valueOf((byte) (((Boolean) elementObject).booleanValue() ? 1 : 0)));
                    }
                } catch (JSONException e) {
                    Trace.debug(PebbleBabel.TAG, "processJsonArrayToBytes", e);
                }
            }
            i = 0;
            this.FinalByteValues = new byte[results.size()];
            Iterator i$ = results.iterator();
            while (i$.hasNext()) {
                Byte b = (Byte) i$.next();
                if (b != null) {
                    this.FinalByteValues[i] = b.byteValue();
                    i++;
                }
            }
            this.FinalByteValues = Arrays.copyOf(this.FinalByteValues, i);
        }

        protected void processStringValuesToBytes() {
            if (this.UnprocessedValues == null) {
                this.FinalByteValues = new byte[0];
            } else if (this.UnprocessedValues.length < 1) {
                this.FinalByteValues = new byte[0];
            } else {
                ArrayList<Byte> results = new ArrayList();
                for (String str : this.UnprocessedValues) {
                    Byte[] candidateArrVal = processSingleStringValue(str);
                    if (candidateArrVal != null && candidateArrVal.length > 0) {
                        results.addAll(Arrays.asList(candidateArrVal));
                    }
                }
                int realCount = 0;
                Iterator i$ = results.iterator();
                while (i$.hasNext()) {
                    if (((Byte) i$.next()) != null) {
                        realCount++;
                    }
                }
                if (this.FinalByteValues != null) {
                    byte[] tmp = Arrays.copyOf(this.FinalByteValues, this.FinalByteValues.length);
                    this.FinalByteValues = new byte[(tmp.length + realCount)];
                    System.arraycopy(tmp, 0, this.FinalByteValues, 0, tmp.length);
                    realCount = tmp.length;
                } else {
                    this.FinalByteValues = new byte[realCount];
                    realCount = 0;
                }
                i$ = results.iterator();
                while (i$.hasNext()) {
                    Byte rb = (Byte) i$.next();
                    if (rb != null) {
                        this.FinalByteValues[realCount] = rb.byteValue();
                        realCount++;
                    }
                }
            }
        }

        protected Byte[] processSingleStringValue(String str) {
            if (str == null || str.length() < 1) {
                return null;
            }
            if (processArrayEntryIntegerRadix10(str) != null) {
                return new Byte[]{processArrayEntryIntegerRadix10(str)};
            }
            if (processArrayEntryIntegerRadix16(str) != null) {
                return new Byte[]{processArrayEntryIntegerRadix16(str)};
            }
            if (processArrayEntryIntegerRadix2(str) != null) {
                return new Byte[]{processArrayEntryIntegerRadix2(str)};
            }
            if (processArrayEntryIntegerRadix8(str) != null) {
                return new Byte[]{processArrayEntryIntegerRadix8(str)};
            }
            if (processArrayEntrySinglechar(str) == null) {
                return processArrayEntryMultichar(str);
            }
            return new Byte[]{processArrayEntrySinglechar(str)};
        }

        protected Byte[] processArrayEntryMultichar(String str) {
            try {
                byte[] b = str.getBytes("UTF-8");
                Byte[] bArr = new Byte[b.length];
                for (int i = 0; i < b.length; i++) {
                    bArr[i] = Byte.valueOf(b[i]);
                }
                return bArr;
            } catch (UnsupportedEncodingException e) {
                Trace.debug(PebbleBabel.TAG, "processArrayEntryMultichar", e);
                return null;
            }
        }

        protected Byte processArrayEntrySinglechar(String str) {
            Byte b = null;
            if (str.length() <= 1) {
                try {
                    byte[] b2 = str.getBytes("UTF-8");
                    if (b2.length > 0) {
                        b = Byte.valueOf(b2[0]);
                    }
                } catch (UnsupportedEncodingException e) {
                    Trace.debug(PebbleBabel.TAG, "processArrayEntrySinglechar", e);
                }
            }
            return b;
        }

        protected Byte processArrayEntryIntegerRadix10(String str) {
            try {
                return Byte.valueOf((byte) (Integer.parseInt(str, 10) % 256));
            } catch (Exception e) {
                Trace.debug(PebbleBabel.TAG, "processArrayEntryIntegerRadix10", e);
                return null;
            }
        }

        protected Byte processArrayEntryIntegerRadix16(String str) {
            try {
                return Byte.valueOf((byte) (Integer.parseInt(str, 16) % 256));
            } catch (Exception e) {
                Trace.debug(PebbleBabel.TAG, "processArrayEntryIntegerRadix16", e);
                return null;
            }
        }

        protected Byte processArrayEntryIntegerRadix8(String str) {
            try {
                return Byte.valueOf((byte) (Integer.parseInt(str, 8) % 256));
            } catch (Exception e) {
                Trace.debug(PebbleBabel.TAG, "processArrayEntryIntegerRadix8", e);
                return null;
            }
        }

        protected Byte processArrayEntryIntegerRadix2(String str) {
            try {
                return Byte.valueOf((byte) (Integer.parseInt(str, 2) % 256));
            } catch (Exception e) {
                Trace.debug(PebbleBabel.TAG, "processArrayEntryIntegerRadix2", e);
                return null;
            }
        }
    }

    public static abstract class JsonFieldNumber extends JsonField {
        public final Number Value;

        public JsonFieldNumber(int appMessageKey, Number value) {
            super(appMessageKey);
            if (value == null) {
                value = new Integer(0);
            }
            this.Value = value;
        }
    }

    public static class JsonFieldInt32 extends JsonFieldNumber {
        public JsonFieldInt32(int appMessageKey, int value) {
            super(appMessageKey, Integer.valueOf(value));
        }

        public PebbleDictionary emit() {
            PebbleDictionary d = new BinaryPebbleDictionary();
            d.addInt32(this.AppMessageIntKey.intValue(), this.Value.intValue());
            return d;
        }

        public PebbleDictionary emitAppended(PebbleDictionary target) {
            if (target == null) {
                return emit();
            }
            target.addInt32(this.AppMessageIntKey.intValue(), this.Value.intValue());
            return target;
        }
    }

    public static class JsonFieldString extends JsonField {
        public final String Value;

        public JsonFieldString(int appMessageKey, String value) {
            super(appMessageKey);
            this.Value = value;
        }

        public PebbleDictionary emit() {
            PebbleDictionary d = new BinaryPebbleDictionary();
            d.addString(this.AppMessageIntKey.intValue(), this.Value);
            return d;
        }

        public PebbleDictionary emitAppended(PebbleDictionary target) {
            if (target == null) {
                return emit();
            }
            target.addString(this.AppMessageIntKey.intValue(), this.Value);
            return target;
        }
    }

    public static abstract class JsonFragment {
        public static final UUID NullUuid = new UUID(0, 0);
        public final UUID mActiveAppUuid;
        public PebbleDictionary mFragmentAppMessageData = null;
        public Map<String, JsonField> mJsonFields;

        protected abstract Map<String, JsonField> createSubSpecificFields(JSONObject jSONObject, Map<String, JsonField> map);

        public JsonFragment(UUID appUuid) {
            if (appUuid == null) {
                appUuid = NullUuid;
            }
            this.mActiveAppUuid = appUuid;
        }

        public AppMessage emitAppMessage() {
            return emitAppMessage(null);
        }

        public AppMessage emitAppMessage(UUID useThisUuid) {
            if (useThisUuid == null) {
                useThisUuid = this.mActiveAppUuid;
            }
            this.mFragmentAppMessageData = new BinaryPebbleDictionary();
            for (JsonField f : this.mJsonFields.values()) {
                this.mFragmentAppMessageData = f.emitAppended(this.mFragmentAppMessageData);
            }
            return new AppMessage(AppMessage.getNextTransactionId(), useThisUuid, AppMessageCommand.PUSH, this.mFragmentAppMessageData);
        }

        public Map<String, JsonField> createFields(JSONObject source, Map<String, JsonField> target) {
            if (target == null) {
                if (this.mJsonFields == null) {
                    this.mJsonFields = makeDefaultEmptyFieldMap();
                }
                target = this.mJsonFields;
            }
            return createSubSpecificFields(source, target);
        }

        public static Map<String, JsonField> makeDefaultEmptyFieldMap() {
            return new HashMap();
        }
    }

    public class JsonFragmentApp extends JsonFragment {
        public JsonFragmentApp(UUID uuid) {
            super(uuid);
        }

        protected Map<String, JsonField> createSubSpecificFields(JSONObject source, Map<String, JsonField> target) {
            if (source != null) {
                Iterator jsonStringKeysIter = source.keys();
                while (jsonStringKeysIter.hasNext()) {
                    String jsonStringKey = (String) jsonStringKeysIter.next();
                    try {
                        Object value = source.get(jsonStringKey);
                        if (value == null) {
                            target.put(jsonStringKey, new JsonFieldString(PebbleBabel.this.appMappingsIntKeyForStringKey(jsonStringKey), source.getString(jsonStringKey)));
                        } else if (value instanceof JSONArray) {
                            target.put(jsonStringKey, new JsonFieldByteArray(PebbleBabel.this.appMappingsIntKeyForStringKey(jsonStringKey), (JSONArray) value));
                        } else if (value instanceof Number) {
                            target.put(jsonStringKey, new JsonFieldInt32(PebbleBabel.this.appMappingsIntKeyForStringKey(jsonStringKey), source.getInt(jsonStringKey)));
                        } else {
                            target.put(jsonStringKey, new JsonFieldString(PebbleBabel.this.appMappingsIntKeyForStringKey(jsonStringKey), source.getString(jsonStringKey)));
                        }
                    } catch (Exception e) {
                        Trace.debug(PebbleBabel.TAG, "createSubSpecificFields", e);
                    }
                }
            }
            return target;
        }

        public void addJsonField(JsonField jsonField) {
            if (jsonField == null) {
                Trace.debug(PebbleBabel.TAG, "addJsonField: jsonField is null");
            } else {
                this.mJsonFields.put("" + jsonField.AppMessageIntKey, jsonField);
            }
        }
    }

    protected static class KeyMappingNotFoundException extends Exception {
        public final String AskedKey;
        public final String AskedSection;

        public KeyMappingNotFoundException() {
            this.AskedSection = "*";
            this.AskedKey = "";
        }

        public KeyMappingNotFoundException(String askedKey) {
            this.AskedSection = "*";
            if (askedKey == null) {
                askedKey = "";
            }
            this.AskedKey = askedKey;
        }
    }

    public static AppInfoBlocks appendNewDataToAppInfoBlocks(AppInfoBlocks appInfoBlocks, String newDataInJsonStringFormat) {
        if (appInfoBlocks == null) {
            appInfoBlocks = new AppInfoBlocks();
        }
        try {
            JSONObject newBlocks = new JSONObject(newDataInJsonStringFormat);
            Iterator it = newBlocks.keys();
            if (newBlocks.has("uuid")) {
                appInfoBlocks.infoBlock = new JSONObject();
                for (String knownKeyName : sAppInfoFixedKeys) {
                    if (newBlocks.has(knownKeyName)) {
                        appInfoBlocks.infoBlock.put(knownKeyName, newBlocks.get(knownKeyName));
                    }
                }
            }
            while (it.hasNext()) {
                try {
                    String keyName = (String) it.next();
                    if (keyName.equals("info") && appInfoBlocks.infoBlock == null) {
                        appInfoBlocks.infoBlock = newBlocks.getJSONObject("info");
                    } else if (keyName.equals("keys") || keyName.equals("app_keys") || keyName.equals("appKeys")) {
                        appInfoBlocks.keysMapBlock = newBlocks.getJSONObject(keyName);
                        appInfoBlocks.keysUpdateSerial++;
                    }
                } catch (Exception e) {
                    Trace.debug(TAG, "appendNewDataToAppInfoBlocks", e);
                }
            }
        } catch (Exception e2) {
            Trace.debug(TAG, "appendNewDataToAppInfoBlocks", e2);
        }
        return appInfoBlocks;
    }

    public static UUID whatIsTheAppUuidInsideTheBlock(AppInfoBlocks appInfoBlocks) {
        UUID uuid = null;
        if (appInfoBlocks == null) {
            Trace.debug(TAG, "whatIsTheAppUuidInsideTheBlock: appInfoBlocks is null");
        } else if (appInfoBlocks.infoBlock == null) {
            Trace.debug(TAG, "whatIsTheAppUuidInsideTheBlock: appInfoBlocks is null");
        } else {
            try {
                String uuidString = appInfoBlocks.infoBlock.optString("uuid", null);
                if (uuidString != null) {
                    uuid = UUID.fromString(uuidString);
                }
            } catch (Exception e) {
                Trace.debug(TAG, "whatIsTheAppUuidInsideTheBlock", e);
            }
        }
        return uuid;
    }

    public UUID updateActiveAppUuidToAppUuidInsideTheBlock(AppInfoBlocks appInfoBlocks) {
        UUID candidateUuid = whatIsTheAppUuidInsideTheBlock(appInfoBlocks);
        UUID u = currentActiveAppUuid();
        if (candidateUuid != null) {
            return (u == null || !u.equals(candidateUuid)) ? setAsActiveAppUuid(candidateUuid) : u;
        } else {
            Trace.debug(TAG, "updateActiveAppUuidToAppUuidInsideTheBlock: candidateUuid is null");
            return u;
        }
    }

    protected static Map<String, Map<String, Integer>> initMappingsForPushMessages() {
        HashMap<String, Map<String, Integer>> topM = new HashMap();
        String[] infoKeys = new String[]{"app", "sent_at", "sent_at_timezone", "source"};
        String[] actionsKeys = new String[]{"expires_at", "on_ok", "on_cancel", "on_delivery", "on_read", "on_deleted", "on_delivery_failure", "on_expiration"};
        String[] metadataKeys = new String[]{"from", "to", GmailCheckerService.EXTRA_ACCOUNT, "time", "timezone", "location_name", "location_lat", "location_lon", "location_radius", "priority"};
        String[] uiKeys = new String[]{"badge", "title", "short_body", "body", "small_icon", "large_icon", "image", "ok_label", "cancel_label", "vibrate"};
        HashMap<String, Integer> m = new HashMap();
        String[] arr$ = infoKeys;
        int len$ = arr$.length;
        int i$ = 0;
        int i = 10;
        while (i$ < len$) {
            int i2 = i + 1;
            m.put(arr$[i$], Integer.valueOf(i));
            i$++;
            i = i2;
        }
        topM.put("info", m);
        m = new HashMap();
        arr$ = actionsKeys;
        len$ = arr$.length;
        i$ = 0;
        i = 100;
        while (i$ < len$) {
            i2 = i + 1;
            m.put(arr$[i$], Integer.valueOf(i));
            i$++;
            i = i2;
        }
        topM.put("actions", m);
        m = new HashMap();
        arr$ = metadataKeys;
        len$ = arr$.length;
        i$ = 0;
        i = 200;
        while (i$ < len$) {
            i2 = i + 1;
            m.put(arr$[i$], Integer.valueOf(i));
            i$++;
            i = i2;
        }
        topM.put("metadata", m);
        m = new HashMap();
        arr$ = uiKeys;
        len$ = arr$.length;
        i$ = 0;
        i = 300;
        while (i$ < len$) {
            i2 = i + 1;
            m.put(arr$[i$], Integer.valueOf(i));
            i$++;
            i = i2;
        }
        topM.put("ui", m);
        GREATEST_HARDCODED_KEY_VALUE = i - 1;
        return topM;
    }

    protected static String[] initAppInfoFixedKeys() {
        return new String[]{"uuid", "shortName", "longName", "versionLabel", "versionCode"};
    }

    protected Map<String, Map<String, Integer>> initMappingsForAppSpecificMessages() {
        HashMap<String, Map<String, Integer>> topM = new HashMap();
        HashMap<String, Integer> m = new HashMap();
        String[] arr$ = sAppInfoFixedKeys;
        int len$ = arr$.length;
        int i$ = 0;
        int i = IMAPStore.RESPONSE;
        while (i$ < len$) {
            int i2 = i + 1;
            m.put(arr$[i$], Integer.valueOf(i));
            i$++;
            i = i2;
        }
        topM.put("info", m);
        return topM;
    }

    protected void addAppMappings(JSONObject block, boolean blockIsInnerKeys) {
        synchronized (this.mStringToIntKeyTranslatorForAppSpecificMessages) {
            Map<String, Integer> appMap = (Map) this.mStringToIntKeyTranslatorForAppSpecificMessages.get("keys");
            if (appMap == null) {
                appMap = new HashMap();
                this.mStringToIntKeyTranslatorForAppSpecificMessages.put("keys", appMap);
            }
            if (!blockIsInnerKeys) {
                block = block.getJSONObject("keys");
                if (block == null) {
                    return;
                }
            }
            try {
                Iterator it = block.keys();
                while (it.hasNext()) {
                    try {
                        String keyName = (String) it.next();
                        appMap.put(keyName, Integer.valueOf(Math.abs(block.getInt(keyName)) + 2000));
                    } catch (Exception e) {
                        Trace.debug(TAG, "addAppMappings", e);
                    }
                }
            } catch (Exception e2) {
                Trace.debug(TAG, "addAppMappings", e2);
            }
        }
    }

    public void addAppMappingsFromInnerKeysSubblock(JSONObject keysSubblock) {
        addAppMappings(keysSubblock, true);
    }

    public int appMappingsIntKeyForStringKey(String key) throws KeyMappingNotFoundException {
        try {
            Map<String, Integer> appKeysSectionMap = (Map) this.mStringToIntKeyTranslatorForAppSpecificMessages.get("keys");
            if (appKeysSectionMap != null) {
                Integer fi = (Integer) appKeysSectionMap.get(key);
                if (fi != null) {
                    return fi.intValue() - 2000;
                }
            }
        } catch (Exception e) {
            Trace.debug(TAG, "appMappingsIntKeyForStringKey", e);
        }
        throw new KeyMappingNotFoundException(key);
    }

    public String appMappingsStringKeyForIntKey(int key) throws KeyMappingNotFoundException {
        try {
            Map<String, Integer> appKeysSectionMap = (Map) this.mStringToIntKeyTranslatorForAppSpecificMessages.get("keys");
            if (appKeysSectionMap != null) {
                for (Entry<String, Integer> entry : appKeysSectionMap.entrySet()) {
                    if (entry != null && ((Integer) entry.getValue()).intValue() == key + 2000) {
                        return (String) entry.getKey();
                    }
                }
            }
        } catch (Exception e) {
            Trace.debug(TAG, "appMappingsStringKeyForIntKey", e);
        }
        throw new KeyMappingNotFoundException("" + key);
    }

    public PebbleBabel() {
        this.mStringToIntKeyTranslatorForAppSpecificMessages = initMappingsForAppSpecificMessages();
        this.mNativeClientAppUuid = NullUuid;
        this.mActiveAppUuid = NullUuid;
    }

    public PebbleBabel(UUID appUuid) {
        this.mStringToIntKeyTranslatorForAppSpecificMessages = initMappingsForAppSpecificMessages();
        if (appUuid == null) {
            appUuid = NullUuid;
        }
        this.mNativeClientAppUuid = appUuid;
        this.mActiveAppUuid = this.mNativeClientAppUuid;
    }

    public UUID currentActiveAppUuid(boolean strictAppUuidOnlyAndNullUuidOtherwise) {
        if (strictAppUuidOnlyAndNullUuidOtherwise) {
            try {
                if (!(this.mActiveAppUuid == null || this.mActiveAppUuid.equals(this.mNativeClientAppUuid))) {
                    return this.mActiveAppUuid;
                }
            } catch (Exception e) {
                Trace.debug(TAG, "currentActiveAppUuid", e);
            }
            return NullUuid;
        } else if (this.mActiveAppUuid != null) {
            return this.mActiveAppUuid;
        } else {
            return this.mNativeClientAppUuid == null ? NullUuid : this.mNativeClientAppUuid;
        }
    }

    public UUID currentActiveAppUuid() {
        return currentActiveAppUuid(false);
    }

    public UUID setAsActiveAppUuid(UUID newActiveAppUuid) {
        UUID t = this.mActiveAppUuid;
        if (newActiveAppUuid == null) {
            newActiveAppUuid = NullUuid;
        }
        this.mActiveAppUuid = newActiveAppUuid;
        return t;
    }

    public AppMessage translateToAppMessage(String appUuidString, String jsonObjectString) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(jsonObjectString);
        } catch (Exception e) {
            Trace.debug(TAG, "translateToAppMessage", e);
        }
        if (jsonObject == null) {
            Trace.debug(TAG, "translateToAppMessage: jsonObject is null");
            return null;
        }
        UUID useAppUuidForMessageMapping = currentActiveAppUuid();
        if (useAppUuidForMessageMapping == null) {
            PebbleWebappBaseActivity.LogSimpleError("%s::%s : current active uuid is null!", getClass().getSimpleName(), "translateToAppMessage", useAppUuidForMessageMapping);
            return null;
        }
        if (appUuidString != null) {
            try {
                UUID u = UUID.fromString(appUuidString);
                if (!(u == null || u.equals(currentActiveAppUuid()))) {
                    PebbleWebappBaseActivity.LogSimpleError("%s::%s : uuid provided as param [%s] doesn't match current active uuid [%s]", getClass().getSimpleName(), "translateToAppMessage", appUuidString, useAppUuidForMessageMapping);
                    return null;
                }
            } catch (Exception e2) {
                Trace.debug(TAG, "translateToAppMessage", e2);
            }
        }
        if (jsonObject.length() == 1) {
            try {
                JSONObject sub = jsonObject.getJSONObject((String) jsonObject.keys().next());
                if (sub != null) {
                    jsonObject = sub;
                }
            } catch (Exception e22) {
                Trace.debug(TAG, "translateToAppMessage", e22);
            }
        }
        PebbleDictionary d = new BinaryPebbleDictionary();
        JsonFragmentApp appFragment = new JsonFragmentApp(useAppUuidForMessageMapping);
        Map<Integer, Object> extractedIntKeys = extractAndRemoveIntegerPseudoKeys(jsonObject);
        appFragment.createFields(jsonObject, null);
        List<JsonField> convertedIntKeys = new ArrayList();
        for (Entry<Integer, Object> entry : extractedIntKeys.entrySet()) {
            if (entry != null) {
                Object getObj = entry.getValue();
                if (getObj != null) {
                    try {
                        if (getObj instanceof JSONArray) {
                            convertedIntKeys.add(new JsonFieldByteArray(((Integer) entry.getKey()).intValue(), (JSONArray) getObj));
                        } else if (getObj instanceof Boolean) {
                            convertedIntKeys.add(new JsonFieldInt32(((Integer) entry.getKey()).intValue(), ((Boolean) getObj).booleanValue() ? 1 : 0));
                        } else if (getObj instanceof Integer) {
                            convertedIntKeys.add(new JsonFieldInt32(((Integer) entry.getKey()).intValue(), ((Integer) getObj).intValue()));
                        } else if (getObj instanceof String) {
                            convertedIntKeys.add(new JsonFieldString(((Integer) entry.getKey()).intValue(), (String) getObj));
                        }
                    } catch (Exception e222) {
                        Trace.debug(TAG, "translateToAppMessage", e222);
                    }
                }
            }
        }
        for (JsonField jsonField : convertedIntKeys) {
            appFragment.addJsonField(jsonField);
        }
        return appFragment.emitAppMessage();
    }

    public Map<Integer, Object> extractAndRemoveIntegerPseudoKeys(JSONObject jsonObject) {
        Map<Integer, Object> rv = new HashMap();
        List<String> removalList = new ArrayList();
        try {
            Iterator<String> jKeys = jsonObject.keys();
            while (jKeys.hasNext()) {
                String key = (String) jKeys.next();
                if (key != null) {
                    try {
                        Integer ikey = Integer.valueOf(Integer.parseInt(key, 10));
                        if (!rv.containsKey(ikey)) {
                            rv.put(ikey, jsonObject.get(key));
                            removalList.add(key);
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        } catch (Exception e2) {
            Trace.debug(TAG, "extractAndRemoveIntegerPseudoKeys", e2);
        }
        for (String removeKey : removalList) {
            jsonObject.remove(removeKey);
        }
        return rv;
    }

    /* JADX WARNING: inconsistent code. */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public org.json.JSONObject translateToJsonObject(com.getpebble.android.framework.appmessage.AppMessage r21) {
        /*
        r20 = this;
        if (r21 != 0) goto L_0x0004;
    L_0x0002:
        r9 = 0;
    L_0x0003:
        return r9;
    L_0x0004:
        r3 = r20.currentActiveAppUuid();
        if (r3 != 0) goto L_0x002f;
    L_0x000a:
        r16 = "%s::%s : current active uuid is null!";
        r17 = 3;
        r0 = r17;
        r0 = new java.lang.Object[r0];
        r17 = r0;
        r18 = 0;
        r19 = r20.getClass();
        r19 = r19.getSimpleName();
        r17[r18] = r19;
        r18 = 1;
        r19 = "translateToJsonObject";
        r17[r18] = r19;
        r18 = 2;
        r17[r18] = r3;
        com.getpebble.android.jskit.webapps.PebbleWebappBaseActivity.LogSimpleError(r16, r17);
        r9 = 0;
        goto L_0x0003;
    L_0x002f:
        r4 = r21.getPebbleDictionary();
        if (r4 != 0) goto L_0x005c;
    L_0x0035:
        r16 = "%s::%s ; uuid = [%s] : no dictionary can be created for appmessage";
        r17 = 3;
        r0 = r17;
        r0 = new java.lang.Object[r0];
        r17 = r0;
        r18 = 0;
        r19 = r20.getClass();
        r19 = r19.getSimpleName();
        r17[r18] = r19;
        r18 = 1;
        r19 = "translateToJsonObject";
        r17[r18] = r19;
        r18 = 2;
        r19 = r21.getUuid();
        r17[r18] = r19;
        com.getpebble.android.jskit.webapps.PebbleWebappBaseActivity.LogSimpleError(r16, r17);
    L_0x005c:
        r13 = r4.iterator();
        r9 = new org.json.JSONObject;
        r9.<init>();
    L_0x0065:
        r16 = r13.hasNext();
        if (r16 == 0) goto L_0x0003;
    L_0x006b:
        r12 = r13.next();
        r12 = (com.getpebble.android.framework.appmessage.PebbleTuple) r12;
        if (r12 == 0) goto L_0x0065;
    L_0x0073:
        r8 = 0;
        r0 = r12.key;	 Catch:{ KeyMappingNotFoundException -> 0x00c7, Exception -> 0x0138 }
        r16 = r0;
        r0 = r20;
        r1 = r16;
        r8 = r0.appMappingsStringKeyForIntKey(r1);	 Catch:{ KeyMappingNotFoundException -> 0x00c7, Exception -> 0x0138 }
    L_0x0080:
        if (r8 != 0) goto L_0x0099;
    L_0x0082:
        r16 = new java.lang.StringBuilder;
        r16.<init>();
        r17 = "";
        r16 = r16.append(r17);
        r0 = r12.key;
        r17 = r0;
        r16 = r16.append(r17);
        r8 = r16.toString();
    L_0x0099:
        r11 = 0;
        r16 = com.getpebble.android.jskit.webapps.PebbleBabel.AnonymousClass1.$SwitchMap$com$getpebble$android$framework$appmessage$PebbleTuple$TupleType;	 Catch:{ Exception -> 0x014b }
        r0 = r12.type;	 Catch:{ Exception -> 0x014b }
        r17 = r0;
        r17 = r17.ordinal();	 Catch:{ Exception -> 0x014b }
        r16 = r16[r17];	 Catch:{ Exception -> 0x014b }
        switch(r16) {
            case 1: goto L_0x00aa;
            case 2: goto L_0x0195;
            case 3: goto L_0x01a2;
            case 4: goto L_0x01b8;
            default: goto L_0x00a9;
        };	 Catch:{ Exception -> 0x014b }
    L_0x00a9:
        goto L_0x0065;
    L_0x00aa:
        r7 = new org.json.JSONArray;	 Catch:{ Exception -> 0x014b }
        r7.<init>();	 Catch:{ Exception -> 0x014b }
        r0 = r12.value;	 Catch:{ Exception -> 0x014b }
        r16 = r0;
        r16 = (byte[]) r16;	 Catch:{ Exception -> 0x014b }
        r0 = r16;
        r0 = (byte[]) r0;	 Catch:{ Exception -> 0x014b }
        r15 = r0;
        r2 = r15;
        r10 = r2.length;	 Catch:{ Exception -> 0x014b }
        r6 = 0;
    L_0x00bd:
        if (r6 >= r10) goto L_0x0146;
    L_0x00bf:
        r14 = r2[r6];	 Catch:{ Exception -> 0x014b }
        r7.put(r14);	 Catch:{ Exception -> 0x014b }
        r6 = r6 + 1;
        goto L_0x00bd;
    L_0x00c7:
        r5 = move-exception;
        r16 = "%s::%s ; uuid = [%s] : key translation not found for tuple-key %d";
        r17 = 4;
        r0 = r17;
        r0 = new java.lang.Object[r0];
        r17 = r0;
        r18 = 0;
        r19 = r20.getClass();
        r19 = r19.getSimpleName();
        r17[r18] = r19;
        r18 = 1;
        r19 = "translateToJsonObject";
        r17[r18] = r19;
        r18 = 2;
        r19 = r21.getUuid();
        r17[r18] = r19;
        r18 = 3;
        r0 = r12.key;
        r19 = r0;
        r19 = java.lang.Integer.valueOf(r19);
        r17[r18] = r19;
        com.getpebble.android.jskit.webapps.PebbleWebappBaseActivity.LogSimpleWarn(r16, r17);
        r16 = "%s::%s ; uuid = [%s] ; tuple-key [%d] : exception = %s";
        r17 = 5;
        r0 = r17;
        r0 = new java.lang.Object[r0];
        r17 = r0;
        r18 = 0;
        r19 = r20.getClass();
        r19 = r19.getSimpleName();
        r17[r18] = r19;
        r18 = 1;
        r19 = "translateToJsonObject";
        r17[r18] = r19;
        r18 = 2;
        r19 = r21.getUuid();
        r17[r18] = r19;
        r18 = 3;
        r0 = r12.key;
        r19 = r0;
        r19 = java.lang.Integer.valueOf(r19);
        r17[r18] = r19;
        r18 = 4;
        r19 = r5.getMessage();
        r17[r18] = r19;
        com.getpebble.android.jskit.webapps.PebbleWebappBaseActivity.LogSimpleWarn(r16, r17);
        goto L_0x0080;
    L_0x0138:
        r5 = move-exception;
        r16 = TAG;
        r17 = "translateToJsonObject";
        r0 = r16;
        r1 = r17;
        com.getpebble.android.common.core.trace.Trace.debug(r0, r1, r5);
        goto L_0x0080;
    L_0x0146:
        r9.put(r8, r7);	 Catch:{ Exception -> 0x014b }
        goto L_0x0065;
    L_0x014b:
        r5 = move-exception;
        r16 = "%s::%s ; uuid = [%s] ; tuple-key [%d] : failure to json.put value of supposed type [%s] (exception = %s";
        r17 = 6;
        r0 = r17;
        r0 = new java.lang.Object[r0];
        r17 = r0;
        r18 = 0;
        r19 = r20.getClass();
        r19 = r19.getSimpleName();
        r17[r18] = r19;
        r18 = 1;
        r19 = "translateToJsonObject";
        r17[r18] = r19;
        r18 = 2;
        r19 = r21.getUuid();
        r17[r18] = r19;
        r18 = 3;
        r0 = r12.key;
        r19 = r0;
        r19 = java.lang.Integer.valueOf(r19);
        r17[r18] = r19;
        r18 = 4;
        r0 = r12.type;
        r19 = r0;
        r19 = r19.toString();
        r17[r18] = r19;
        r18 = 5;
        r19 = r5.getMessage();
        r17[r18] = r19;
        com.getpebble.android.jskit.webapps.PebbleWebappBaseActivity.LogSimpleError(r16, r17);
        goto L_0x0065;
    L_0x0195:
        r0 = r12.value;	 Catch:{ Exception -> 0x014b }
        r16 = r0;
        r16 = (java.lang.String) r16;	 Catch:{ Exception -> 0x014b }
        r0 = r16;
        r9.put(r8, r0);	 Catch:{ Exception -> 0x014b }
        goto L_0x0065;
    L_0x01a2:
        r0 = r12.value;	 Catch:{ Exception -> 0x014b }
        r16 = r0;
        r16 = (java.lang.Number) r16;	 Catch:{ Exception -> 0x014b }
        r0 = r16;
        r0 = (java.lang.Number) r0;	 Catch:{ Exception -> 0x014b }
        r11 = r0;
        r16 = r11.longValue();	 Catch:{ Exception -> 0x014b }
        r0 = r16;
        r9.put(r8, r0);	 Catch:{ Exception -> 0x014b }
        goto L_0x0065;
    L_0x01b8:
        r0 = r12.value;	 Catch:{ Exception -> 0x014b }
        r16 = r0;
        r16 = (java.lang.Number) r16;	 Catch:{ Exception -> 0x014b }
        r0 = r16;
        r0 = (java.lang.Number) r0;	 Catch:{ Exception -> 0x014b }
        r11 = r0;
        r16 = r11.intValue();	 Catch:{ Exception -> 0x014b }
        r0 = r16;
        r9.put(r8, r0);	 Catch:{ Exception -> 0x014b }
        goto L_0x0065;
        */
        throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.jskit.webapps.PebbleBabel.translateToJsonObject(com.getpebble.android.framework.appmessage.AppMessage):org.json.JSONObject");
    }
}
